/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package history;

import avenue.Session;
import avenue.messageBox;
import java.awt.Color;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import model.Card;
import model.DBManager;
import model.Station;
import model.Vehicle;

/**
 *
 * @author me
 */
public class historyPassesForm extends javax.swing.JFrame {

    /**
     * Creates new form historyPassesForm
     */
    public historyPassesForm() {
         em = DBManager.em;
        initComponents();
        for(int i=0;i<=jComboBox1.getItemCount()-1;i++) //Βρες τον Σταθμό του χρήστη στο combo
        { 
        Station ss=(Station) jComboBox1.getItemAt(i);
            if (ss.getDescription()==Session.loginUser.getStationId().getDescription())
            {
            jComboBox1.setSelectedIndex(i);
            break;
            }
        }
        
        if (Session.loginUser.getRoleId().getId()!=1){
            jComboBox1.setEnabled(false);
        }
        else
        {jComboBox1.setEnabled(true);
        
        }
           getContentPane().setBackground(Color.white);
        //Στοιχιση στο κέντρο 24/2/2013
        setLocationRelativeTo(null);
        
        //Αρχικες τιμες στις ημερομηνίες
        Calendar calendar = Calendar.getInstance();
        Date today=calendar.getTime();
         jenddate.setDate(today);//Σημερινη ημερομηνία
        
        
         calendar.set(2000, 0, 1);
        today=calendar.getTime();//Αρχη εργασίων το 2000
        
       
        jstartdate.setDate(today);
        
        
        //Καθαρισμός της λίστας
        collectionList.clear();
                   
       
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        collectionQuery = java.beans.Beans.isDesignTime() ? null : em.createQuery("SELECT c FROM Collection c");
        collectionList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : collectionQuery.getResultList();
        query1 = java.beans.Beans.isDesignTime() ? null : em.createQuery("select v from Vehicle v");
        list1 = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : query1.getResultList();
        query2 = java.beans.Beans.isDesignTime() ? null : em.createQuery("select ca from Card ca");
        list2 = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query2.getResultList());
        query3 = java.beans.Beans.isDesignTime() ? null : em.createQuery("select s from Station s");
        list3 = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query3.getResultList());
        stationBoxRenderer1 = new avenue.StationBoxRenderer();
        jLabel9 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        arKikloforias = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jbarcode = new javax.swing.JTextField();
        jButton3 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jstartdate = new com.toedter.calendar.JDateChooser();
        jenddate = new com.toedter.calendar.JDateChooser();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox();
        jLabel10 = new javax.swing.JLabel();

        stationBoxRenderer1.setText("stationBoxRenderer1");

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel9.setFont(new java.awt.Font("Snap ITC", 1, 24)); // NOI18N
        jLabel9.setForeground(new java.awt.Color(0, 3, 130));
        jLabel9.setText("TelePass 1.0");

        jLabel8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/imagesCAL4A9SX.jpg"))); // NOI18N

        jLabel7.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel7.setText("Ιστορικό Διελεύσεων");

        jLabel1.setText("Αρ. Κυκλοφορίας: ");

        jLabel2.setText("Αρ. Κάρτας (barcode): ");

        jbarcode.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbarcodeActionPerformed(evt);
            }
        });

        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/cog.png"))); // NOI18N
        jButton3.setText("Ευρεση");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, collectionList, jTable1);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${cardId.barcode}"));
        columnBinding.setColumnName("Barcode κάρτας");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${tollCollected}"));
        columnBinding.setColumnName("Ποσό διοδίων");
        columnBinding.setColumnClass(java.math.BigDecimal.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${passTimestamp}"));
        columnBinding.setColumnName("Ημερομηνία");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jScrollPane1.setViewportView(jTable1);
        jTable1.getColumnModel().getColumn(0).setResizable(false);
        jTable1.getColumnModel().getColumn(1).setResizable(false);
        jTable1.getColumnModel().getColumn(2).setResizable(false);

        jLabel4.setText("Εως :");

        jLabel5.setText("Από : ");

        jComboBox1.setRenderer(stationBoxRenderer1);

        org.jdesktop.swingbinding.JComboBoxBinding jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, list3, jComboBox1, "st");
        bindingGroup.addBinding(jComboBoxBinding);

        jLabel10.setText("Σταθμός: ");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(6, 6, 6)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel9)
                            .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(77, 77, 77)
                        .addComponent(jLabel1)
                        .addGap(39, 39, 39)
                        .addComponent(arKikloforias, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(27, 27, 27)
                        .addComponent(jLabel5)
                        .addGap(16, 16, 16)
                        .addComponent(jstartdate, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(77, 77, 77)
                        .addComponent(jLabel2)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel10)
                                .addGap(13, 13, 13)
                                .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(22, 22, 22)
                                .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jbarcode, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(27, 27, 27)
                                .addComponent(jLabel4)
                                .addGap(19, 19, 19)
                                .addComponent(jenddate, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 599, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(27, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(6, 6, 6)
                        .addComponent(jLabel7)))
                .addGap(28, 28, 28)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(5, 5, 5)
                        .addComponent(jLabel1))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(2, 2, 2)
                        .addComponent(arKikloforias, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel5)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(2, 2, 2)
                        .addComponent(jstartdate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(6, 6, 6)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(3, 3, 3)
                        .addComponent(jLabel2))
                    .addComponent(jbarcode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(2, 2, 2)
                        .addComponent(jLabel4))
                    .addComponent(jenddate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(29, 29, 29)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(jLabel10)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton3))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 520, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jbarcodeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbarcodeActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jbarcodeActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
      Vehicle v;
      Boolean found=true;
      
      
      if  (arKikloforias.getText().isEmpty()==false) {//Εχει αριθμο κυκλοφοριας
           query1 = em.createQuery("select v from Vehicle v where v.regNumber=:regNumber").setParameter("regNumber", arKikloforias.getText());
            List <Vehicle> list1 = query1.getResultList();

                 if (list1.size()==1) {// Υπάρχει το όχημα?

                            v = list1.get(0);

                            if (jbarcode.getText().isEmpty()==false){ //Εχει γραψει barcode
                                        int bar=0;
                                         try{
                                              bar=Integer.parseInt(jbarcode.getText());}
                                         catch(NumberFormatException nfe){
                                         }

                                       if (v.getCardId().getBarcode()==bar){// το βρήκε

                                           collectionQuery = em.createQuery("select c from Collection c where c.cardId=:cardid and c.passTimestamp>=:startD and c.passTimestamp<=:endD and c.stationId=:station order by c.passTimestamp DESC").setParameter("cardid", v.getCardId()).setParameter("startD",jstartdate.getDate()).setParameter("endD",jenddate.getDate()).setParameter("station",jComboBox1.getSelectedItem());

                                           }
                                       else{
                                           messageBox.infoBox("Δεν υπάρχει αντιστοιχία μεταξύ κάρτας και οχήματος");
                                           found=false;
                                          }
                            }
                            else //Μόνο αριθμό κυκλοφορίας 
                            { collectionQuery = em.createQuery("select c from Collection c where c.cardId=:cardid and c.passTimestamp>=:startD and c.passTimestamp<=:endD and c.stationId=:station order by c.passTimestamp DESC").setParameter("cardid", v.getCardId()).setParameter("startD",jstartdate.getDate()).setParameter("endD",jenddate.getDate()).setParameter("station",jComboBox1.getSelectedItem());
                            }
                    }
              else{//Δεν υπάρχει αυτο οχήμα
                      messageBox.infoBox("Δεν υπάρχει αυτο οχήμα");
                      found=false;
                   }
                 
      }
        else//Δεν εχει  γραψει αριθμο κυκλοφοριας 
            {
              if (jbarcode.getText().isEmpty()==false){ //Εχει barcode οχι αριθμος κυκλοφοριας
                    int bar=Integer.parseInt(jbarcode.getText());
                       query2 = em.createQuery("select ca from Card ca where ca.barcode=:cardId").setParameter("cardId", bar);
                        list2 = query2.getResultList();
                     if (list2.size()>=1) {// Υπάρχει το όχημα?

                            Card ca = (Card)list2.get(0);
                            collectionQuery = em.createQuery("select c from Collection c where c.cardId=:cardid and c.passTimestamp>=:startD and c.passTimestamp<=:endD and c.stationId=:station order by c.passTimestamp DESC").setParameter("cardid", ca).setParameter("startD",jstartdate.getDate()).setParameter("endD",jenddate.getDate()).setParameter("station",jComboBox1.getSelectedItem());
                        }
                     else
                        { messageBox.infoBox("Δεν υπάρχει αυτή η κάρτα");
                        found=false;
                        }
              }
              else{//Δεν εχει barcode οχι αριθμος κυκλοφοριας
                  
                  collectionQuery = em.createQuery("select c from Collection c where c.passTimestamp>=:startD and c.passTimestamp<=:endD and c.stationId=:station order by c.passTimestamp DESC").setParameter("startD",jstartdate.getDate()).setParameter("endD",jenddate.getDate()).setParameter("station",jComboBox1.getSelectedItem());
                
              }
              
              
            }
                   

        
        if (found){
              java.util.Collection data = collectionQuery.getResultList();
                    for (Object entity : data) {
                        em.refresh(entity);
                    }
                    collectionList.clear();
                    collectionList.addAll(data);
                    jTable1.revalidate();
        }
        else
        {collectionList.clear();
        jTable1.revalidate();
        }
 
    }//GEN-LAST:event_jButton3ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(historyPassesForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(historyPassesForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(historyPassesForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(historyPassesForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new historyPassesForm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField arKikloforias;
    private java.util.List<model.Collection> collectionList;
    private javax.persistence.Query collectionQuery;
    private javax.swing.JButton jButton3;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jbarcode;
    private com.toedter.calendar.JDateChooser jenddate;
    private com.toedter.calendar.JDateChooser jstartdate;
    private java.util.List list1;
    private java.util.List list2;
    private java.util.List list3;
    private javax.persistence.Query query1;
    private javax.persistence.Query query2;
    private javax.persistence.Query query3;
    private avenue.StationBoxRenderer stationBoxRenderer1;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
EntityManager em;
}
